#include "DirectXSprite.h"
int m_frameWidth;
int m_frameHeight;
int m_texWidth;
int m_texHeight;
int m_numFrames;

DirectXSprite::DirectXSprite()
	: m_frameWidth(0)
	, m_frameHeight(0)
	, m_texWidth(0)
	, m_texHeight(0)
	, m_numFrames(0)
{

}

void DirectXSprite::LoadTexture( int frameWidth, int frameHeight, LPDIRECT3DDEVICE9 device, LPCWSTR fileName )
{
	m_frameWidth = frameWidth;
	m_frameHeight = frameHeight;

	HRESULT result =  D3DXCreateTextureFromFile(device, fileName, &m_texture);
	D3DSURFACE_DESC surfaceDesc;
	m_texture->GetLevelDesc(0, &surfaceDesc); 
	m_texWidth = surfaceDesc.Width;
	m_texHeight = surfaceDesc.Height;
	m_numFrames = static_cast<int>( ( surfaceDesc.Width / frameWidth ) * ( surfaceDesc.Height / frameHeight ) );
	
	D3DXCreateSprite(device,&m_sprite);
}


DirectXSprite::~DirectXSprite()
{
}

void DirectXSprite::Release()
{
	m_texture->Release();
	m_sprite->Release();
}

void DirectXSprite::Draw( int frame, float rotation, float xPos, float yPos, bool flipped )
{	
	int numHorizontalFrame( m_texWidth / m_frameWidth );

	int horizontalFrame( frame % numHorizontalFrame );
	int verticalFrame( frame / numHorizontalFrame );
	
	LONG    left( horizontalFrame * m_frameWidth );
	LONG    top( verticalFrame * m_frameHeight );
	LONG    right( ( horizontalFrame * m_frameWidth ) + m_frameWidth );
	LONG    bottom( ( verticalFrame * m_frameHeight ) + m_frameHeight );
	RECT sourceRect;
	sourceRect.left = left;
	sourceRect.right = right;
	sourceRect.top = top;
	sourceRect.bottom = bottom;

	D3DXMATRIX matRotation, matTranslate, matFinal;

	//x rotation (NEW)
	


	D3DXMatrixTranslation(&matTranslate,xPos,yPos,1);
	

	D3DXMatrixRotationZ(&matRotation, rotation * 0.0174532925f );
	if( flipped )
	{
		D3DXMATRIX matFlipRotZ, matFlipRotX;
		D3DXMatrixRotationZ(&matFlipRotZ, ( rotation + 180.f) * 0.0174532925f );
		D3DXMatrixRotationX(&matFlipRotX, 180.f * 0.0174532925f );

		
		D3DXMatrixMultiply(&matRotation,&matFlipRotX, &matFlipRotZ);
		D3DXMatrixTranslation(&matTranslate,xPos + m_frameWidth,yPos,1);
	}

	D3DXMatrixMultiply(&matFinal, &matRotation, &matTranslate);
	
	
	m_sprite->Begin(D3DXSPRITE_ALPHABLEND);
	//m_SimpleSurfaceShader.Effect->BeginPass(0);
	m_sprite->SetTransform(&matFinal);
	m_sprite->Draw(m_texture,&sourceRect,NULL,NULL, 0xFFFFFFFF );
	//m_SimpleSurfaceShader.Effect->EndPass();
	m_sprite->End();
}

LPDIRECT3DTEXTURE9 DirectXSprite::GetTexture()
{
	return m_texture;
}